const fs = require('fs')
const url = require('url')
const path = require('path')
const express = require('express')
const template = require('art-template')
const config = require('./config')
const bodyParser = require('body-parser')
const app = express()
app.use(express.static('assets'));
app.engine('html',require('express-art-template'))
app.set('view engine','html');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/*', function (req, res) {
  const styleFilePath = path.resolve(__dirname, '../assets/db/attr.css')
  let userStyle = ''
  if (fs.existsSync(styleFilePath)) {
    userStyle = fs.readFileSync(styleFilePath).toString()
  }
  const tdkFilePath = path.resolve(__dirname, '../assets/db/tdk.json')
  let userTdk = {}
  if (fs.existsSync(tdkFilePath)) {
    userTdk = JSON.parse(fs.readFileSync(tdkFilePath))
  }
  const {pathname} = url.parse(req.url, true)
  res.render(pathname.substring(1), {
    url: config.host,
    header: 'header',
    userStyle,
    userTdk
  })
})

app.post('/api/attrSet', function(req, res) {
  const filePath = path.resolve(__dirname, '../assets/db/attr.css')
  let str = ''
  if (fs.existsSync(filePath)) {
    const data = fs.readFileSync(filePath).toString()
    str += data ? data + '\n' : ''
  }
  str += req.body.str
  fs.writeFileSync(filePath, str)
  res.json(true)
})
app.post('/api/tdkSet', function(req, res) {
  const filePath = path.resolve(__dirname, '../assets/db/tdk.json')
  fs.writeFileSync(filePath, JSON.stringify(req.body))
  res.json(true)
})
app.listen(3000, () => {
  console.log('server is running')
})
